package top.yongyan0624.utils;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.support.spring.PropertyPreFilters;
import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.request.AlipayTradePagePayRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import top.yongyan0624.common.dto.AlipayDto;
import top.yongyan0624.config.AlipayConfig;
import top.yongyan0624.entity.Alipay;
import top.yongyan0624.entity.AlipayGroup;

/**
 * @author Yongyan
 * @description: TODO
 * @date 2021/9/11
 **/
@Component
public class AlipayUtils {

    @Autowired
    private AlipayConfig alipayConfig;

    /**
     * 支付接口
     *
     * @param alipay
     * @return
     * @throws AlipayApiException
     */
    public String pay(Alipay alipay) throws AlipayApiException {
        // 1、获得初始化的AlipayClient
        String serverUrl = alipayConfig.getGatewayUrl();
        String appId = alipayConfig.getAppId();
        String privateKey = alipayConfig.getPrivateKey();
        String format = "json";
        String charset = alipayConfig.getCharset();
        String alipayPublicKey = alipayConfig.getPublicKey();
        String signType = alipayConfig.getSignType();
        String returnUrl = alipayConfig.getReturnUrl();
        String notifyUrl = alipayConfig.getNotifyUrl();
        AlipayClient alipayClient = new DefaultAlipayClient(serverUrl, appId, privateKey, format, charset, alipayPublicKey, signType);
        // 2、设置请求参数
        AlipayTradePagePayRequest alipayRequest = new AlipayTradePagePayRequest();
        // 页面跳转同步通知页面路径
        alipayRequest.setReturnUrl(returnUrl);
        // 服务器异步通知页面路径
        alipayRequest.setNotifyUrl(notifyUrl);
        // 封装参数
        // 设置字段过滤，只包含下面六个参数
        AlipayDto alipayDto = new AlipayDto(alipay.getOutTradeNo(), alipay.getSubject(), alipay.getTotalAmount(), alipay.getBody(), alipay.getTimeout_express(), alipay.getProduct_code());
        alipayRequest.setBizContent(JSON.toJSONString(alipayDto));
        // 3、请求支付宝进行付款，并获取支付结果
        String result = alipayClient.pageExecute(alipayRequest).getBody();
        // 返回付款信息
        return result;
    }

    public String pay(AlipayGroup alipayGroup) throws AlipayApiException {
        return pay(new Alipay()
                .setOutTradeNo(alipayGroup.getOut_trade_no())
                .setSubject(alipayGroup.getSubject())
                .setTotalAmount(alipayGroup.getTotal_amount())
                .setBody(alipayGroup.getBody()));
    }
}
